﻿using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel.Composition;
using Caliburn.Micro;
using Example.Entities;
using Example.Transports.Order;
using Zero.Common;
using Zero.Frontend;

namespace Example.Frontend.Customers
{
    [Export]
    public class CustomerOrdersViewModel : Screen
    {
        public CustomerOrdersViewModel()
        {
            DisplayName = "Orders";
        }

        private Customer _customer;
        public Customer Customer
        {
            get { return _customer; }
            set
            {
                if (_customer != value)
                {
                    _customer = value;

                    if (IsActive) ReloadOrdersAsync();

                    NotifyOfPropertyChange(()=>Customer);
                }
            }
        }

        private readonly ObservableCollection<Order> _orders = new ObservableCollection<Order>();
        public ReadOnlyObservableCollection<Order> Orders
        {
            get { return new ReadOnlyObservableCollection<Order>(_orders); }
        }

        protected override void OnActivate()
        {
            base.OnActivate();

            ReloadOrdersAsync();
        }

        private void ReloadOrdersAsync()
        {
            var context = new ActionExecutionContext { Target = this };
            Coroutine.BeginExecute(ReloadOrdersCorout().GetEnumerator(), context);
        }

        private IEnumerable<IResult> ReloadOrdersCorout()
        {
            if (Customer == null)
            {
                _orders.Clear();

                yield break;
            }

            yield return Show.Busy();

            var req = new GetOrdersByCustomer() {CustomerId = _customer.Id}.AsRequest();

            yield return req;

            _orders.ClearAndAddRange(req.Result.Orders);

            yield return Show.NotBusy();          
        }
    }
}